//
//  HomeViewController.m
//  欢乐美食
//
//  Created by 遇水 on 15/6/24.
//  Copyright (c) 2015年 遇水. All rights reserved.
//

#import "HomeViewController.h"
#import "HTHorizontalSelectionList.h"

#import "MSFoots.h"          //
#import "MSMetaDataTool.h"    //元数据工具类

#import "historyTool.h"
#import "MJRefresh.h"

#import "StoreViewCell.h"

#import "MSDeals.h"

#import "CitySelectedController.h"
#import "SingerDealController.h"

#import "UIImageView+WebCache.h"
#import "StoreViewCell.h"
@interface HomeViewController ()<HTHorizontalSelectionListDataSource,HTHorizontalSelectionListDelegate,UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong) HTHorizontalSelectionList *textSelectionList;
@property (nonatomic, strong) NSArray *headerViewDataSource;   //顶部的数据

@property (nonatomic, strong) UITableView    *tableView;        //用于显示数据

@property (nonatomic, strong)   NSMutableArray  *dealArray;      //所有的团购


@property (nonatomic, strong) NSString    *selectedIndexStr;   //选中的内容


@property (nonatomic, strong) MSFindDealsParam    *param;

@end

@implementation HomeViewController


-(NSMutableArray *)dealArray{
    if (_dealArray==nil) {
        _dealArray = [NSMutableArray array];
    }

    return _dealArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //默认进来    选中的内容为空，默认加载西北菜
    [self loadNewDeals];     //加载一次
    [self initHeaderView];
    [self initTableView];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"location"] style:UIBarButtonItemStyleDone target:self action:@selector(location)];

}

-(void)viewWillAppear:(BOOL)animated
{
    UILabel *city = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [city setText:[[NSUserDefaults standardUserDefaults]stringForKey:@"city"]];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:city];
}



-(void)location
{
    //push进新的界面选择地址
    CitySelectedController *citySelected = [[CitySelectedController alloc]init];
    [self.navigationController pushViewController:citySelected animated:YES];
}


-(void)initHeaderView
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //添加控件
    self.textSelectionList = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    self.textSelectionList.delegate = self;
    self.textSelectionList.dataSource = self;
    
    //属性设置
    self.textSelectionList.selectionIdicatorAnimationMode = HTHorizontalSelectionIndicatorAnimationModeLightBounce;
    
    self.textSelectionList.selectionIndicatorColor = [UIColor redColor];
    [self.textSelectionList setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [self.textSelectionList setTitleFont:[UIFont systemFontOfSize:13] forState:UIControlStateNormal];
    [self.textSelectionList setTitleFont:[UIFont boldSystemFontOfSize:13] forState:UIControlStateSelected];
    [self.textSelectionList setTitleFont:[UIFont boldSystemFontOfSize:13] forState:UIControlStateHighlighted];
    
    
    MSFoots *foots = [MSMetaDataTool sharedMetaDataTool].foots[0];
    NSArray *subFoot = foots.subcategories;

//    //设置显示的数据

    self.headerViewDataSource = subFoot;

    //添加到view中去
    [self.view addSubview:self.textSelectionList];
}

-(void)initTableView
{
    UITableView *tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, self.view.width, self.view.height - 44)];
    //    [tableview autoSetDimension:ALEdgeTop toSize:5];
    tableview.dataSource = self;
    tableview.delegate = self;
    tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableview];
    self.tableView = tableview;
    
//添加下来刷新，上啦加载更多控件
    tableview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewDeals];
        [tableview.header endRefreshing];

    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    tableview.header.autoChangeAlpha = YES;
    // 上拉刷新
    tableview.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{

        [self loadMoreDeals];
        [tableview.footer endRefreshing];
    
    }];
//
}

#pragma mark - 刷新数据
- (void)loadNewDeals
{
    MSFindDealsParam *param = [[MSFindDealsParam alloc] init];
    // 城市名称
    NSString *city = [[NSUserDefaults standardUserDefaults]stringForKey:@"city"];
    param.city = @"北京";
    if (city != nil) {
        param.city = city;
    }
     param.category = @"西北菜";
    if(self.selectedIndexStr.length > 0){
        param.category = self.selectedIndexStr;
    }

    self.param = param;
    [MSDealTool findDeals:param success:^(MSFindDealsResult *result) {
        
        if (result.deals.count == 0) {
            [MBProgressHUD showError:@"请求结果为空"];
        }
        
        // 清空之前的所有数据
        [self.dealArray removeAllObjects];
        
        // 添加新的数据
        [self.dealArray addObjectsFromArray:result.deals];
        // 刷新表格
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.dealArray removeAllObjects];
        [self.tableView reloadData];
        [MBProgressHUD showError:@"加载团购失败，请稍后再试"];
    }];
}

- (void)loadMoreDeals
{

    MSFindDealsParam *paramMore = self.param;
    paramMore.page = @(self.param.page.intValue + 1);
    [MSDealTool findDeals:self.param success:^(MSFindDealsResult *result) {
        //添加新数据
        [self.dealArray addObjectsFromArray:result.deals];
        
        [self.tableView reloadData];
        
        
    } failure:^(NSError *error) {
        
    }];

}


#pragma mark - tableView的代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dealArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    StoreViewCell *cell = (StoreViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.height;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cell";
    StoreViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell ==nil) {
        cell =  [[[NSBundle mainBundle]loadNibNamed:@"StoreViewCell" owner:nil options:nil]firstObject];
    }
    cell.deal  =  self.dealArray[indexPath.item];
    return  cell;
}

//选中cell的时候调用
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //push
    SingerDealController *singerDealVC = [[SingerDealController alloc]init];
    MSDeals *deal  = self.dealArray[indexPath.item];
#warning 保存浏览记录
    //保存浏览记录
    [[historyTool sharedhistoryTool] saveHistoryDeal:deal];
    
    singerDealVC.deal = deal;
    singerDealVC.dealD = deal.deal_id;
    [self.navigationController pushViewController:singerDealVC animated:YES];
}



#pragma  mark - 顶部控件的代理方法
- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList {
    return self.headerViewDataSource.count;
}

- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index {
    return self.headerViewDataSource[index];
}

#pragma mark - HTHorizontalSelectionListDelegate Protocol Methods
//当选中时的状态
- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index {

    self.selectedIndexStr = self.headerViewDataSource[index];
    NSLog(@"%@",self.selectedIndexStr);
    //每点击一次加载一次数据
    [self loadNewDeals];
    
}


@end
